/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lambkit.module.common.service;

import cn.hutool.core.util.StrUtil;
import com.lambkit.core.Lambkit;
import com.lambkit.db.AbstractDaoService;
import com.lambkit.db.DbPool;
import com.lambkit.db.IRowDao;
import com.lambkit.module.common.CommonConfig;
import com.lambkit.module.common.SettingConfigCenter;
import com.lambkit.module.common.row.Setting;
import com.lambkit.module.common.sql.SettingSQL;

/**
 * @author yangyong 
 * @website: www.lambkit.com
 * @email: gismail@foxmail.com
 * @date ${date}
 * @version 1.0
 * @since 1.0
 */

public class SettingService extends AbstractDaoService<Setting> {
	public static SettingService of() {
		return Lambkit.get(SettingService.class);
	}
	public IRowDao<Setting> dao() {
		String dbPoolName = Lambkit.config(CommonConfig.class, SettingConfigCenter.class).getDbPoolName();
		return DbPool.use(dbPoolName).dao(Setting.class);
	}

	public IRowDao<Setting> dao(String dbPoolName) {
		return DbPool.use(dbPoolName).dao(Setting.class);
	}


	public Setting findByKey(String key) {
		return dao().findFirst(SettingSQL.of().andSettingKeyEqualTo(key).example());
	}

	public String get(String key) {
		Setting setting = dao().findFirst(SettingSQL.of().andSettingKeyEqualTo(key).example());
		return setting!=null ? setting.getSettingValue() : null;
	}

	public void remove(String key) {
		dao().delete(SettingSQL.of().andSettingKeyEqualTo(key).example());
		Lambkit.configCenter().clearConfig();
	}

	public void put(String key, String value) {
		if(StrUtil.isBlank(key) || StrUtil.isBlank(value)) {
			return;
		}
		if(StrUtil.isBlank(value)) {
			remove(key);
			return;
		}
		Setting setting = dao().findFirst(SettingSQL.of().andSettingKeyEqualTo(key).example());
		if(setting==null) {
			setting = new Setting();
		}
		setting.setSettingKey(key);
		setting.setSettingValue(value);
		dao().saveOrUpdate(setting);
	}
}
